package com.yue.util;

/**
 * 功能描述: TODO <br/>
 * 创建时间: 2016/10/11<br/>
 *
 * @author QiuYang
 */
public class IPTools {

    /**
     * convert hexadecimal String IP without prefix to decimal String IP with '.' separator
     * example： 0a1b6340 -> 10.27.99.64
     * @param hexIp
     * @return
     */
    public static String hexToDecIp(String hexIp) throws Exception{
        if (!validateHexIp(hexIp)) {
            throw new RuntimeException("hexadecimal data invalidate!");
        }
        String[] ipElements = StringTools.split(hexIp, 2);

        StringBuilder builder = new StringBuilder();
        for (String ipElement : ipElements) {
            builder.append(Integer.parseInt(ipElement, 16)).append(".");
        }
        builder.delete(builder.lastIndexOf("."), builder.length() + 1);

        return builder.toString();
    }

    /**
     * validate hexadecimal String IP without prefix
     * example: hexIp:"0a1b6340", result:true;
     *          hexIp:"0a1b634035", result:false;   too long
     *          hexIp:"0aib642g", result:false;     obtain invalidate characters
     * @param hexIp
     * @return
     */
    public static boolean validateHexIp(String hexIp) {
        if (hexIp.length() != 8) {
            return false;
        }

        return validateHexWithoutPrefix(hexIp);
    }

    /**
     * validate hexadecimal String without prefix
     * example: hexStr:"0a1b6340534", result:true;
     *          hexStr:"0aib642g", result:false;     obtain invalidate characters('i', 'g')
     * @param hexStr
     * @return
     */
    public static boolean validateHexWithoutPrefix(String hexStr){
        String[] strBit = StringTools.split(hexStr, 1);
        final String hexValidataStr = "0123456789abcdefABCDEF";
        for (String s : strBit) {
            if (!hexValidataStr.contains(s)) {
                return false;
            }
        }

        return true;
    }
}
